<template>
  <div class="onekey-inspection-container">
    <div class="header" :header="pageTile">
      <a-button class="back-button" @click="gotoBack"> 返回 </a-button>
    </div>
    <div class="onekey-inspection-body">
      <div class="main">
        <div class="container">
          <a-form-model ref="ruleForm" :model="ruleForm">
            <div
              class="process-item-container"
              v-for="(item, index) in basicData"
              :key="index"
            >
              <div class="item-header">
                <div class="title">工序信息（{{ index + 1 }}）</div>
                <div
                  class="delete-btn"
                  v-if="!item.loading"
                  @click="deleteCard(index)"
                >
                  删除
                </div>
              </div>
              <div class="process-step-container" v-loading="!item.loaded">
                <processesCard
                  v-if="item.loaded"
                  :operateMode="item.operateMode"
                  :forms.sync="item.formList"
                  @handleSelect="handleSelect($event, item.formList, index)"
                  @fileChange="handleFileChange($event)"
                  @fileDownload="download($event)"
                  @filePreview="viewFile($event)"
                ></processesCard>
              </div>
            </div>
          </a-form-model>
        </div>
        <div class="add-process-button flex" @click="add()">+ 新增报验工序</div>
      </div>
      <div class="footer" v-if="basicData.length > 0">
        <a-button @click="gotoBack()">取消</a-button>
        <!-- <a-button
          @click="onSubmit(2)"
          :loading="zcLoading"
          :disabled="basicData.length == 0 || tjLoading"
        >
          暂存
        </a-button> -->
        <a-button
          type="primary"
          @click="onSubmit(1)"
          :loading="tjLoading"
          :disabled="basicData.length == 0 || zcLoading"
        >
          提交
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
//一键报验
import bjUploadFile from "@/components/bj-upload-file";
import bjUploadImg from "@/components/bj-upload-img";
import processesCard from "./components/processesCard";
import {
  getInspectionInit,
  getGXSelectData,
  uploadFileByType,
  submitProcedure,
  bYJLDetails,
  getSelfTestPeople,
} from "@/api/wisdom-beam/quality-app";
import { downFileByUrl, commonViewFile } from "@/utils";
import { getLoginData } from "@/tools";
export default {
  components: {
    bjUploadFile,
    bjUploadImg,
    processesCard,
  },
  data() {
    return {
      pageTile: "一键报验",
      zcLoading: false,
      tjLoading: false,
      ruleForm: {},
      basicData: [],
      dynamicForms: {},
      pargeInitSource: {},
      //自检人
      selfPeopleSelect: [],
    };
  },
  mounted() {
    this.getPeopleData();
    let { title } = this.$route.query;
    this.pageTile = title ?? "一键报验";
    this.$nextTick(() => {
      this.initPage();
    });
  },
  methods: {
    //下载附件
    download(file) {
      let { imagePath, realFileName } = file;
      downFileByUrl(imagePath, realFileName);
    },

    //附件预览
    viewFile(file) {
      let { id } = file;
      commonViewFile("beam", id);
    },

    //初始化页面
    initPage() {
      try {
        let { id } = this.$route.query;
        let records = JSON.parse(sessionStorage.getItem("oneKeyInspection"));
        this.basicData = records;
        let requetQueue = this.basicData.map((v, i) => {
          this.$set(v, "loaded", true);
          this.$set(v, "operateMode", "editor");
          return this.getInspectionInit(v);
        });

        //查询详情
        if (id) {
          Promise.all(requetQueue).then((res) => {
            this.getDetails(id);
          });
        }
      } catch (error) {
        this.basicData = [];
        return new Error(error);
      }
    },

    //查询详情
    getDetails(id) {
      return new Promise((resolve, reject) => {
        bYJLDetails({ id })
          .then((res) => {
            let { data } = res;
            let list = data?.result?.scheduleWbsProcedureList || [];
            list.forEach((v, i) => {
              let { formdetails, hierarchy, rangeValue } = v;
              this.basicData[i].formList.forEach((form) => {
                let { key } = form;
                //层级
                if (key == "cengji") {
                  this.$set(form, "defalutValue", Number(hierarchy));
                }
                //幅别
                if (key == "rangeValue") {
                  this.$set(form, "defalutValue", Number(rangeValue));
                }

                //施工部位
                if (key == "sjsgbw") {
                  let keys = [
                    "positionKey1",
                    "positionKey2",
                    "positionKey3",
                    "positionKey4",
                    "positionKey5",
                    "positionKey6",
                  ];
                  keys.forEach((sgbw) => {
                    this.$set(
                      form,
                      sgbw,
                      v[sgbw] == null ? undefined : Number(v[sgbw])
                    );
                  });
                }
              });
              formdetails.forEach((item) => {
                let { elementKey, elementType, elementValue, fileList } = item;
                let currentForm = this.basicData[i].formList.find(
                  (v) => v.key == elementKey
                );
                //文本框
                if (elementType == "1" || elementType == "2") {
                  this.$set(currentForm, "defalutValue", elementValue);
                }

                //附件
                if (
                  elementType == "3" ||
                  elementType == "4" ||
                  elementType == "5"
                ) {
                  this.$set(currentForm, "defalutValue", fileList || []);
                }

                //位置
                if (elementType == "6") {
                  this.$set(currentForm, "defalutValue", elementValue);
                }

                //
              });
            });
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //新增 loading
    add() {
      let froms = this.buildDefaultForm(this.pargeInitSource, "add");
      let addKeys = ["orgName", "unitWorks", "divisionalWorks"];
      let initForms = froms.filter((v) => addKeys.includes(v.key));
      let { orgCode, unitWorks } = this.$route.query;
      let item = initForms.find((v) => v.key == "divisionalWorks");
      item.loading = true;
      item.nextShowFlag = false;
      this.basicData.push({
        loaded: true,
        operateMode: "add",
        formList: initForms,
      });

      //
      this.getGXSelectData({ orgCode, unitWorks })
        .then((res) => {
          let { nextShowFlag, selectList } = res;
          item.nextShowFlag = nextShowFlag;
          item.selectDatas = selectList;
        })
        .catch((_) => {
          item.nextShowFlag = false;
          item.selectDatas = [];
        })
        .finally((_) => {
          item.loading = false;
        });
    },

    //监听select
    async handleSelect(ev, formsData, itemIdx) {
      let { key, index } = ev;
      let paramsKeys = [
        "divisionalWorks",
        "subDivisionalWorks",
        "itemWorks",
        "subItemWorks",
      ];
      if (!paramsKeys.includes(key) && key != "procedureItem") {
        return false;
      }
      let { orgCode, unitWorks } = this.$route.query;
      let froms = this.buildDefaultForm(this.pargeInitSource, "add");
      let addKeys = ["orgName", "unitWorks", "divisionalWorks"];

      let currenKey = "";
      let params = {};
      formsData.forEach((v) => {
        let { key, defalutValue } = v;
        if (paramsKeys.includes(key)) {
          params[key] = defalutValue;
        }
      });

      if (key == "procedureItem") {
        //工序
        this.getFormsData(formsData, itemIdx);
      } else {
        this.getGXSelectData({ orgCode, unitWorks, ...params })
          .then((res) => {
            let { nextShowFlag, selectList } = res;
            switch (key) {
              case "divisionalWorks":
                if (nextShowFlag == true) {
                  currenKey = "subDivisionalWorks";
                } else {
                  currenKey = "itemWorks";
                }
                break;

              case "subDivisionalWorks":
                if (nextShowFlag == true) {
                  currenKey = "itemWorks";
                } else {
                  currenKey = "subItemWorks";
                }
                break;

              case "itemWorks":
                if (nextShowFlag == true) {
                  currenKey = "subItemWorks";
                } else {
                  currenKey = "procedureItem";
                }
                break;

              case "subItemWorks":
                currenKey = "procedureItem";
                break;

              default:
                break;
            }
            let hasItem = formsData.some((b) => b.key == currenKey);
            !addKeys.includes(currenKey) && addKeys.push(currenKey);
            let initForms = froms.filter((v) => addKeys.includes(v.key));
            let item = initForms.find((v) => v.key == currenKey);
            !hasItem && formsData.splice(index + 1, 0, item);
            item.nextShowFlag = nextShowFlag;
            item.selectDatas = selectList;
          })
          .catch((_) => {
            // item.nextShowFlag = false;
            // item.selectDatas = [];
          });
      }
    },

    //监听附件上传
    handleFileChange(ev) {
      let { file, defalutValue } = ev;
      let formData = new FormData();
      formData.append("uploadFile", file);
      uploadFileByType(formData, "WBS_PROCEDURE")
        .then((res) => {
          let { data } = res;
          this.$set(
            defalutValue[defalutValue.length - 1],
            "id",
            data?.result?.fileId || ""
          );
        })
        .catch((_) => {});
    },

    //查询动态表单数据
    getFormsData(formsData, index) {
      let { orgCode, unitWorks } = this.$route.query;
      let { userId } = getLoginData();
      const element = this.isElementExistsById(this.selfPeopleSelect, userId);
      let paramKeys = [
        "divisionalWorks",
        "subDivisionalWorks",
        "itemWorks",
        "subItemWorks",
        "procedureItem",
      ];
      let params = {};
      formsData.forEach((v) => {
        let { key } = v;
        if (paramKeys.includes(key)) {
          params[key] = v.defalutValue;
        }
      });
      return new Promise((resolve, reject) => {
        getInspectionInit("", { orgCode, unitWorks, ...params })
          .then((res) => {
            let { data } = res;
            let source = data?.result || [];
            //处理 附件、图片、视频 类型的默认值
            (source.wWorkflowForms || []).forEach((v) => {
              let { elementType, defalutValue } = v;
              if (
                elementType == "3" ||
                elementType == "4" ||
                elementType == "5"
              ) {
                if (!Array.isArray(defalutValue)) {
                  if (defalutValue) {
                    v.defalutValue = defalutValue.split(",");
                  } else {
                    v.defalutValue = [];
                  }
                }
              }
            });
            let {
              cengjiShow,
              cengjiSelect,
              rangeSelect,
              sjsgbwShow,
              wWorkflowForms,
              scheduleWbs,
              sjsgbwSelect,
            } = source;
            let forms = [
              {
                elementName: "幅别",
                key: "rangeValue",
                disabled: 0,
                elementType: "select",
                defalutValue: undefined,
                elementRequired: "0",
                selectDatas: rangeSelect || [],
                loading: false,
                $$formType: 0,
              },
              {
                elementName: "是否合格",
                key: "result",
                disabled: 0,
                elementType: "radio",
                defalutValue: "0",
                elementRequired: "0",
                selectDatas: [],
                loading: false,
                $$formType: 0,
              },
              {
                elementName: "自检人",
                key: "selfCheckPerson",
                disabled: 0,
                elementType: "zjr",
                defalutValue: element ? userId : undefined,
                elementRequired: "0",
                selectDatas: this.selfPeopleSelect || [],
                loading: false,
                $$formType: 0,
              },
            ];
            if (cengjiShow) {
              forms.push({
                elementName: "层级",
                key: "cengji",
                disabled: 0,
                elementType: "select",
                defalutValue: undefined,
                elementRequired: "0",
                selectDatas: cengjiSelect || [],
                loading: false,
                $$formType: 0,
              });
            }
            if (sjsgbwShow) {
              forms.push({
                elementName: "施工部位",
                key: "sjsgbw",
                disabled: 0,
                elementType: "sgbw",
                defalutValue: undefined,
                elementRequired: "0",
                selectDatas: sjsgbwSelect || [],
                loading: false,
                positionKey1: undefined,
                positionKey2: undefined,
                positionKey3: undefined,
                positionKey4: undefined,
                positionKey5: undefined,
                positionKey6: undefined,
                $$formType: 0,
              });
            }
            formsData = formsData.concat(forms);
            this.$set(this.basicData, index, {
              ...this.basicData[index],
              ...scheduleWbs,
              formList: [...formsData, ...wWorkflowForms],
              scheduleWbsId: scheduleWbs.id,
            });
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //根据id查询详情
    getInspectionInit(item) {
      let { id } = item;
      return new Promise((resolve, reject) => {
        getInspectionInit(id, {})
          .then((res) => {
            let { data } = res;
            let source = data?.result || {};
            this.pargeInitSource = source;
            //处理 附件、图片、视频 类型的默认值
            (source?.wWorkflowForms || []).forEach((v) => {
              let { elementType, defalutValue } = v;
              if (
                elementType == "3" ||
                elementType == "4" ||
                elementType == "5"
              ) {
                if (!Array.isArray(defalutValue)) {
                  if (defalutValue) {
                    v.defalutValue = defalutValue.split(",");
                  } else {
                    v.defalutValue = [];
                  }
                }
              }
            });
            this.$set(item, "scheduleWbsId", source?.scheduleWbs?.id || "");
            this.$set(item, "formList", [
              ...this.buildDefaultForm(source || {}, "editor"),
              ...(source?.wWorkflowForms || []),
            ]);
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {
            this.$set(item, "loaded", true);
          });
      });
    },

    //构件默认表单数据
    buildDefaultForm(item = {}, mode = "editor") {
      let { userId } = getLoginData();
      const element = this.isElementExistsById(this.selfPeopleSelect, userId);
      let routeQuery = this.$route.query;
      let {
        divisionalWorks,
        subDivisionalWorks,
        itemWorks,
        subItemWorks,
        procedureItem,
        orgCode,
        unitWorks,
        orgName,
      } = item?.scheduleWbs || {};
      let { cengjiShow, cengjiSelect, sjsgbwShow, rangeSelect, sjsgbwSelect } =
        item;
      let dynamicKeys = [
        "subDivisionalWorks",
        "itemWorks",
        "subItemWorks",
        "procedureItem",
      ];
      let forms = [
        {
          elementName: "标段名称",
          key: "orgName",
          disabled: 1,
          elementType: "1",
          defalutValue:
            routeQuery.inspectionStatus == 0 ? routeQuery.orgName : orgName,
          elementRequired: "0",
          orgCode,
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "单位工程",
          key: "unitWorks",
          disabled: 1,
          elementType: "1",
          defalutValue:
            routeQuery.inspectionStatus == 0 ? routeQuery.unitWorks : unitWorks,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分部工程",
          key: "divisionalWorks",
          disabled: mode == "editor" ? 1 : 0,
          elementType: "select",
          defalutValue: mode == "editor" ? divisionalWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分部子工程",
          key: "subDivisionalWorks",
          disabled: mode == "editor" ? 1 : 0,
          elementType: "select",
          defalutValue: mode == "editor" ? subDivisionalWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分项工程",
          key: "itemWorks",
          disabled: mode == "editor" ? 1 : 0,
          elementType: "select",
          defalutValue: mode == "editor" ? itemWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "子分项工程",
          key: "subItemWorks",
          disabled: mode == "editor" ? 1 : 0,
          elementType: "select",
          defalutValue: mode == "editor" ? subItemWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "工序",
          key: "procedureItem",
          disabled: mode == "editor" ? 1 : 0,
          elementType: "select",
          defalutValue: mode == "editor" ? procedureItem : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "施工部位",
          key: "sjsgbw",
          disabled: 0,
          elementType: "sgbw",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: sjsgbwSelect || [],
          loading: false,
          $$formType: 0,
          positionKey1: undefined,
          positionKey2: undefined,
          positionKey3: undefined,
          positionKey4: undefined,
          positionKey5: undefined,
          positionKey6: undefined,
        },
        {
          elementName: "幅别",
          key: "rangeValue",
          disabled: 0,
          elementType: "select",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: rangeSelect || [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "是否合格",
          key: "result",
          disabled: 0,
          elementType: "radio",
          defalutValue: "0",
          elementRequired: "0",
          selectDatas: [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "自检人",
          key: "selfCheckPerson",
          disabled: 0,
          elementType: "zjr",
          defalutValue: element ? userId : undefined,
          elementRequired: "0",
          selectDatas: this.selfPeopleSelect || [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "层级",
          key: "cengji",
          disabled: 0,
          elementType: "select",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: cengjiSelect || [],
          loading: false,
          $$formType: 0,
        },
      ];

      //是否展示层级
      if (!cengjiShow) {
        forms = forms.filter((v) => v.key != "cengji");
      }

      //是否展示施工部位
      if (!sjsgbwShow) {
        forms = forms.filter((v) => v.key != "sjsgbw");
      }

      if (mode == "editor") {
        forms = forms.filter((v) => {
          let { key } = v;
          if (dynamicKeys.includes(key)) {
            if (item?.scheduleWbs[key]) {
              return v;
            }
          } else {
            return v;
          }
        });
      }

      return forms;
    },

    //查询下拉框数据
    getGXSelectData(param) {
      return new Promise((resolve, reject) => {
        getGXSelectData(param)
          .then((res) => {
            let { data } = res;
            let { nextShowFlag, selectList } = data?.result || {};
            let sList = [];
            selectList.forEach((v) => {
              sList.push({
                dicValue: v,
                dicDesc: v,
              });
            });
            resolve({ nextShowFlag, selectList: sList });
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询自检人
    getPeopleData() {
      let { orgCode } = this.$route.query;
      return new Promise((resolve, reject) => {
        getSelfTestPeople({ orgCode })
          .then((res) => {
            let { data } = res;
            let selectList = data?.result || [];
            let sList = [];
            selectList.forEach((v) => {
              sList.push({
                dicValue: v.approveUserId,
                dicDesc: v.approveUser,
              });
            });
            this.selfPeopleSelect = sList;
            resolve();
          })
          .catch((_) => {
            this.selfPeopleSelect = [];
            reject();
          });
      });
    },
    isElementExistsById(arr, id) {
      // 使用数组的find方法查找元素
      const element = arr.find((item) => item.dicValue === id);
      // 如果找到了元素，则返回true，否则返回false
      return !!element;
    },
    //模拟提交
    onSubmit(type) {
      let { orgCode, unitWorks } = this.$route.query;
      let saveInfo = [];
      this.basicData.forEach((v, i) => {
        let { formList } = v;
        saveInfo.push({
          scheduleWbsId: v.scheduleWbsId,
          formData: [],
        });
        formList.forEach((item) => {
          let { $$formType, key, defalutValue } = item;
          if ($$formType == 0) {
            if (key == "cengji") {
              //层级
              saveInfo[i].hierarchy = defalutValue;
            } else if (key == "sjsgbw") {
              //施工部位
              let {
                positionKey1,
                positionKey2,
                positionKey3,
                positionKey4,
                positionKey5,
                positionKey6,
              } = item;
              saveInfo[i].positionKey1 = positionKey1;
              saveInfo[i].positionKey2 = positionKey2;
              saveInfo[i].positionKey3 = positionKey3;
              saveInfo[i].positionKey4 = positionKey4;
              saveInfo[i].positionKey5 = positionKey5;
              saveInfo[i].positionKey6 = positionKey6;
            } else {
              saveInfo[i][key] = defalutValue;
            }
          } else {
            let { key, defalutValue } = item;
            saveInfo[i].formData.push({
              elementKey: key,
              elementValue: Array.isArray(defalutValue)
                ? defalutValue.map((v) => v.id).toString()
                : defalutValue || "",
            });
          }
        });
      });
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          switch (type) {
            case 1:
              this.tjLoading = true;
              break;

            case 2:
              this.zcLoading = true;
              break;

            default:
              break;
          }
          this.requestInterface({ orgCode, unitWorks, type, saveInfo });
        } else {
          console.log("error submit!!");
        }
      });
    },

    //请求提交接口
    requestInterface(params) {
      let { id } = this.$route.query;
      if (id) {
        params.applyParentId = id;
      }
      return new Promise((resolve, reject) => {
        submitProcedure(params)
          .then((res) => {
            let { data } = res;
            if (data?.result) {
              this.$message.success("操作成功");
              this.gotoBack();
            } else {
              this.$message.error("操作失败，请稍后重试！");
            }
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {
            this.tjLoading = false;
            this.zcLoading = false;
          });
      });
    },

    //返回
    gotoBack() {
      let { orgCode, unitWorks, backPath } = this.$route.query;
      sessionStorage.removeItem("oneKeyInspection");
      this.$router.push({
        path: backPath ?? "/nebula/wisdom-beam-app/procedure/startInspection",
        query: {
          orgCode,
          unitWorks,
        },
      });
    },

    //删除
    deleteCard(index) {
      this.basicData = this.basicData.filter((_, i) => i != index);
    },
  },
  destroyed() {
    // sessionStorage.removeItem("oneKeyInspection");
  },
};
</script>

<style lang="less" scoped>
.onekey-inspection-container {
  box-sizing: border-box;
  height: 100%;
  .flex();
  flex-direction: column;
  .header {
    padding: 18px 20px;
    margin-left: 10px;
    background-color: #fff;
    box-sizing: border-box;
    margin-bottom: 1px;
    .flex();
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
    &::before {
      content: attr(header);
      height: 18px;
      border-left: 3px solid var(--primary-color);
      padding-left: 10px;
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #525a5d;
      line-height: 18px;
    }
    .back-button {
      color: var(--primary-color);
      background: #f1f2f7 !important;
      border: none;
    }
  }
  .onekey-inspection-body {
    flex: 1;
    .custom-scrollbar();
    margin-left: 10px;
    background: #fff;
    .main {
      flex-direction: column;
      padding-bottom: 10px;
      .container {
        padding: 10px 30px 0 30px;
        .process-item-container {
          .item-header {
            .flex();
            justify-content: space-between;
            height: 50px;
            color: var(--primary-color);
            font-size: 16px;
            padding: 20px 0 10px 0;
            .title {
              .flex();
              align-items: center;
              &::before {
                content: "";
                .flex();
                width: 6px;
                height: 6px;
                background: var(--primary-color);
                border-radius: 50%;
                margin-right: 10px;
              }
            }
            .delete-btn {
              cursor: pointer;
            }
          }
          .process-step-container {
            //   min-height: 400px;
          }
        }
      }
      .add-process-button {
        height: 36px;
        background: rgba(55, 89, 160, 0.1);
        border: 1px dashed var(--primary-color);
        align-items: center;
        justify-content: center;
        color: var(--primary-color);
        margin: 10px 30px 0 30px;
        cursor: pointer;
      }
    }

    .footer {
      flex-shrink: 0;
      height: 70px;
      margin-left: 10px;
      .flex();
      align-items: center;
      justify-content: center;
      background: #fff;
      margin-top: 1px;
    }
  }
}
</style>
